const fs = require("fs");
const PDFDocument = require("pdfkit");

exports.createFileWithPath = function (dirPath) {
  if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath, { recursive: true });
  }
};

exports.genPdfFile = (outputPath, content) => {
  // 创建一个 PDF 文档对象
  const doc = new PDFDocument();
  doc.font("./fonts/simsun.ttf");
  // 将字符串添加到 PDF 文档中
  doc.text(content);

  // 将 PDF 文档保存到本地文件
  doc.pipe(fs.createWriteStream(outputPath));
  doc.end();
};

 function fetchWithRetry (url, options = {}, retriesLeft = 5) {
  return fetch(url, options).then((response) => {
    if (retriesLeft > 0 && !response.data) {
      return fetchWithRetry(url, options, retriesLeft - 1);
    }
    return response;
  });
};

exports.fetchWithRetry = fetchWithRetry

exports.sanitizeFileName = function (fileName) {
  fileName = fileName.replace(/\//g, "_");
  // 定义不合法的字符集
  const illegalCharacters = /[\/:*?"<>|]/;
  // 替换不合法字符为空字符串
  return fileName.replace(illegalCharacters, "");
};




